package api

import (
	"encoding/json"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"web_api_gogf/app/model"
	"web_api_gogf/app/service"
	"web_api_gogf/library/response"
)

// SysRole 角色管理接口
var SysRole = SysRoleApi{}

type SysRoleApi struct {
}

// Index 首页列表
func (s *SysRoleApi) Index(r *ghttp.Request) {
	var searchParams *model.SysRoleGetListReq
	if err := r.Parse(&searchParams); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	//角色列表
	roleList, err := service.SysRole.GetList(searchParams)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	var roleTreeList []*model.SysRoleTree
	if searchParams.Name == "" && searchParams.DisplayName == "" {
		roleTreeOriginList := ([]model.SysRoleTree)(nil)
		gconv.Structs(roleList, &roleTreeOriginList)
		//还原json字段
		for k, data := range roleTreeOriginList {
			var per []string
			_ = json.Unmarshal([]byte(data.PermIds), &per)
			roleTreeOriginList[k].PermIdsArr = per
		}
		roleTreeList = service.SysRole.BuildTree(roleTreeOriginList)
	} else {
		gconv.Structs(roleList, &roleTreeList)
	}
	//权限列表
	permList, err := service.SysPermission.GetAll()
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	permTreeOriginList := ([]model.SysPermissionTree)(nil)
	gconv.Structs(permList, &permTreeOriginList)
	permTreeList := service.SysPermission.BuildTree(permTreeOriginList)
	response.Json(r, 0, "加载成功", g.Map{
		"roleList": roleTreeList,
		"permList": permTreeList,
	})
}

// Save 保存角色数据
func (s *SysRoleApi) Save(r *ghttp.Request) {
	var roleData *model.SysRoleSaveReq
	if err := r.Parse(&roleData); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	err := service.SysRole.SaveRole(roleData)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.Json(r, 0, "保存成功")
}

// Destroy 删除角色
func (s *SysRoleApi) Destroy(r *ghttp.Request) {
	var roleIds []uint
	recRoleIds := r.Get("role_ids")
	roleIds = gconv.SliceUint(recRoleIds)
	if roleIds == nil {
		response.JsonExit(r, 1, "请选择要删除的角色")
	}
	err := service.SysRole.DelRole(roleIds)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.Json(r, 0, "删除成功")
}
